package com.jingxi.rest.service;
import com.jingxi.rest.mapper.TbItemCatMapper;
import com.jingxi.rest.model.TbItemCat;
import com.jingxi.rest.model.TbItemCatExample;
import com.jingxi.rest.model.TbItemCatExample.Criteria;
import com.jingxi.rest.pojo.CatNode;
import com.jingxi.rest.pojo.CatResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemCatServiceImpl implements ItemCatService {
    @Autowired
    private TbItemCatMapper itemCatMapper;

    @Override
    public CatResult getItemCatList() {
        CatResult catResult = new CatResult();//查询分类列表
        catResult.setData(getCatList(0));
        return catResult;
    }

    /*** 查询分类列表* <p>Title: getCatList</p>* <p>Description: </p>* @param parentId* @return*/
    public List<?> getCatList(long parentId) {
        //创建查询条件
        TbItemCatExample example = new TbItemCatExample();
        Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        //执行查询
        List<TbItemCat> list = itemCatMapper.selectByExample(example);
        //返回值list
        List resultList = new ArrayList<>();
        //向list中添加节点
        int count = 0;
        for (TbItemCat tbItemCat : list) {
            //判断是否为父节点
            if (tbItemCat.getIsParent()) {
                CatNode catNode = new CatNode();
                if (parentId == 0) {//根据parentId判断级联 0 1 2
                    catNode.setName("<a href='/products/" +
                            tbItemCat.getId() +
                            ".html'>" + tbItemCat.getName() +
                            "</a>");
                } else {
                    catNode.setName(tbItemCat.getName());//1级联 名称
                }
                catNode.setUrl("/products/" + tbItemCat.getId() + ".html");
                catNode.setItem(getCatList(tbItemCat.getId()));//进入递归 parentId等于tbItemCat.getId()
                //找出对应的子级联 tbItemCat.getId()等于下标
                // 递归实现
                // 下级目录查询后放在该catNode的item
                // 子级联parent_id等于父id
                resultList.add(catNode);
                count++;
                //第一层只取14条记录
                if (parentId == 0 && count >= 14) {
                    break;
                }
            }
            //如果是叶子节点
            else
            {
                resultList.add("/products/" + tbItemCat.getId() + ".html|" + tbItemCat.getName());
            }
        }
        return resultList;
    }
}
